<template>
  <div class="table">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 帖子列表
        </el-breadcrumb-item>
        <el-button type="primary" class="add-vest" @click="showAddPost">发布帖子</el-button>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-select v-model="getPostData['schoolId']" placeholder="筛选学校" class="handle-select mr10">
          <el-option
            v-for="school in schoolList"
            :key="school['Name']"
            :label="school['Name']"
            :value="school['SchoolId']"
          ></el-option>
        </el-select>
        <el-select
          v-model="getPostData['categoryId']"
          placeholder="选择分类"
          class="handle-select mr10"
        >
          <el-option
            v-for="category in categoryList"
            :key="category['Name']"
            :label="category['Name']"
            :value="category['CategoryId']"
          ></el-option>
        </el-select>
        <el-select v-model="getPostData['status']" placeholder="选择状态" class="handle-select mr10">
          <el-option key="1" label="正常" value="1"></el-option>
          <el-option key="2" label="待审核" value="2"></el-option>
        </el-select>
        <el-select v-model="getPostData['sort']" placeholder="排序" class="handle-select mr10">
          <el-option key="1" label="ID升序" value="idAsc"></el-option>
          <el-option key="2" label="ID倒序" value="idDesc"></el-option>
          <el-option key="3" label="评论数升序" value="commentNumAsc"></el-option>
          <el-option key="4" label="评论数倒序" value="commentNumDesc"></el-option>
          <el-option key="5" label="点赞数升序" value="likeNumAsc"></el-option>
          <el-option key="6" label="点赞数倒序" value="likeNumDesc"></el-option>
        </el-select>
        <el-input
          v-model="getPostData['nickname']"
          placeholder="输入用户昵称(模糊)"
          class="handle-input mr10"
        ></el-input>
        <el-input
          v-model="getPostData['content']"
          placeholder="输入帖子内容(模糊)"
          class="handle-input mr10"
        ></el-input>
        <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      </div>
      <el-table :data="postList" border class="table" ref="multipleTable">
        <el-table-column prop="PostId" label="ID" width="120"></el-table-column>
        <el-table-column label="用户头像" sortable width="150" align="center">
          <template slot-scope="scope">
            <img :src="scope.row.Avatar" alt srcset class="user-head" />
          </template>
        </el-table-column>
        <el-table-column prop="Nickname" label="用户昵称" width="120"></el-table-column>
        <el-table-column prop="Content" label="发帖内容" width="120"></el-table-column>
        <el-table-column label="图片/视频" align="center" width="300px">
          <template slot-scope="scope">
            <div v-if="scope.row.Images" class="source-box">
              <el-carousel height="150px">
                <el-carousel-item v-for="item in scope.row.imgArr" :key="item">
                  <img :src="item" alt class="source" />
                </el-carousel-item>
              </el-carousel>
            </div>
            <div v-if="scope.row.Videos" class="source-box">
              <video :src="scope.row['Videos']" class="source" controls></video>
            </div>
            <div v-if="!scope.row.Videos&&!scope.row.Images">
              <h5>没有图片/视频</h5>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="CreateTime" label="发布时间"></el-table-column>
        <el-table-column prop="LikeNum" label="点赞数"></el-table-column>
        <el-table-column prop="CommentNum" label="评论数"></el-table-column>
        <el-table-column prop="FollowNum" label="关注数"></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              :class="scope.row.IsDisplay==1?'red':''"
              :icon="scope.row.IsDisplay==1?'el-icon-download':'el-icon-upload2'"
              @click="handleEdit(scope.$index, scope.row)"
            >{{scope.row.IsDisplay==1?"下架":"上架"}}</el-button>
            <el-button type="text" icon="el-icon-view" @click="preview(scope.$index)">预览</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          :page-size="pageSize"
          @current-change="handleCurrentChange"
          layout="prev, pager, next"
          :total="postTotalCount"
        ></el-pagination>
      </div>
    </div>
    <!-- 展示预览二维码 -->
    <div class="pre-view-box" v-if="preViewCode" @click="closePreview">
      <img :src="codeUrl" />
    </div>
    <!-- 添加新帖子 -->
    <div class="add-post-box" v-show="showAddPostState">
      <i class="el-icon-close" @click="closeAddPost"></i>
      <div class="add-post-form">
        <div class="form-item">
          <span class="form-item-title">选择学校：</span>
          <el-select v-model="selectedId" placeholder="选择学校" class="handle-select handle-select-sub mr10">
            <el-option
            v-for="(school,index) in schoolList"
            v-show="index>0"
            :key="school['Name']"
            :label="school['Name']"
            :value="school['SchoolId']"
          ></el-option>
          </el-select>
        </div>
        <div class="form-item">
          <span class="form-item-title">马甲号：</span>
          <el-select v-model="pulishCon['userId']" placeholder="选择马甲号" class="handle-select handle-select-sub mr10">
            <el-option
              v-for="user in userList"
              v-show="selectedId==''||(selectedId==user['SchoolId'])"
              :key="user.Nickname"
              :label="user.Nickname"
              :value="user.UserId"
            ></el-option>
          </el-select>
        </div>
        <div class="form-item">
          <span class="form-item-title">选择分类：</span>
          <el-select
            v-model="pulishCon['categoryId']"
            placeholder="选择分类"
            class="handle-select handle-select-sub mr10"
          >
            <el-option
              v-for="(category,index) in categoryList"
              v-show="index>0"
              :key="category['Name']"
              :label="category['Name']"
              :value="category['CategoryId']"
            ></el-option>
          </el-select>
        </div>
        <div class="form-item">
          <span class="form-item-title">帖子内容：</span>
          <el-input
            class="post-con"
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="pulishCon['content']"
          ></el-input>
        </div>
        <div class="form-item">
          <span class="form-item-title">上传图片/视频：</span>
          <div class="source-list">
              <div class="source-item"  v-for="(img,index) in imgs" :key="img['data']['url']" v-show="imgs.length>0">
                  <img :src="img['data']['url']" alt="">
                  <i class="el-icon-close remove-btn" @click="removepic('img',index)"></i>
              </div>
              <div class="source-item"  v-for='(video,index) in videos' :key="video['data']['url']" v-show="videos.length>0">
                  <video :src="video['data']['url']" controls></video>
                  <i class="el-icon-close remove-btn"  @click="removepic('video',index)"></i>
              </div>
              <div class="source-item" v-show="(firstType=='video'&&videos.length==0)||(imgs.length<9&&firstType=='image')">
                  <i class="el-icon-plus"></i>
                  <input type="file" class="uploadFile" multiple="multiple" @change="beforeUpload">
              </div>
          </div>
        </div>
        <div class="form-item" v-if='pulishCon["categoryId"]==2'>
          <span class="form-item-title">投票选项：</span>
          <ul class="vote-list">
            <li v-for="(vote,index) in voteList" :key="index">
              <div class="img-box">
                <i class="el-icon-plus" v-if="vote['image']==''"></i>
                <img :src="vote['image']" alt="" srcset="" v-else>
                <input type="file" class="uploadFile" @change="uploadVotePic" :index="index">
              </div>
              <div class="txt-box">
                <el-input v-model="vote['text']" :placeholder="`编辑选项${index+1}`" class="txt-input"></el-input>
                <el-button type="danger" v-if="index>1"  icon="el-icon-delete" circle class="delBtn" @click="delVote(index)"></el-button>
              </div>
            </li>
            <el-button type="primary" icon="el-icon-circle-plus-outline" @click="addVote">添加选项</el-button>
          </ul>
        </div>
        <div class="form-item" v-if='pulishCon["categoryId"]==2'>
          <span class="form-item-title">是否多选：</span>
          <el-switch
            class="voteTypeSwitch"
            v-model="pulishCon['voteInfo']['type']"
            active-color="#13ce66"
            active-value="2"
            inactive-value="1">
          </el-switch>
        </div>
        <div class="form-item" v-if='pulishCon["categoryId"]==2'>
          <span class="form-item-title">投票截止时间：</span>
          <el-date-picker
            v-model="pulishCon['voteInfo']['expire']"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
          </el-date-picker>
        </div>
        <div class="form-item">
          <el-button type="primary" class="add-post-btn" @click="publish">提交</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import QRCode from "qrcode";
import { getUserList } from "../../api/user";
import { getPostList, subPost, publishPost } from "../../api/post";
import { getSchoolList } from "../../api/school";
import { getCatogoryList } from "../../api/category";
import { uploadFile } from "../../api/upload";
import { setTimeout } from 'timers';
export default {
  name: "basetable",
  data() {
    return {
      schoolList: [],
      postList: [],
      categoryList: [],
      userList: [],
      pageSize: 0,
      postTotalCount: 0,
      getPostData: {
        Page: 1,
        PageSize: 10,
        postId: 0,
        userId: 0,
        nickname: "",
        schoolId: "",
        categoryId: "",
        status: "",
        content: "",
        isDel: "",
        sort: ""
      },
      codeUrl: "",
      preViewCode: false,
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      baseUrl:this.$baseUrl,
      fileList:[],
      sourceType:1,
      imgs:[],
      videos:[],
      firstType:'video',
      isfirst:false,
      showAddPostState:false,
      selectedId:'',
      voteList:[{
        text:"",
        image:""
      },
      {
        text:"",
        image:""
      }
    ],
      pulishCon: {
        userId: "",
        categoryId: "",
        content: "",
        images: "",
        videos: "",
        location: "",
        voteInfo: {
          type: 1,
          expire: "",
          items: []
        }
      }
    };
  },
  created() {
    this.getData();
    this._getSchoolList();
    this._getCategoryList();
    this._getUserList();
  },
  methods: {
    handleRemove(file) {
        let fileList = this.fileList;
        fileList.forEach((f,index)=>{
            if(f.name==file.name){
                fileList.splice(index,1);
            }
        })
        this.fileList = fileList;
    },
    handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
    },
    beforeUpload(e){
        let files = e.target.files;
        let firstType = files[0]['type'].split('/')[0];
        let newFiles = [];
        if(!this.isfirst){
          this.isfirst = true;
          this.firstType = firstType;
        }
        if(firstType=='video'){
            if(this.firstType!=firstType){
              return false;
            }
            newFiles = [files[0]]
        }else{
            if(this.firstType!=firstType){
              return false;
            }
            Object.keys(files).forEach(index=>{
                if(files[index]['type'].split('/')[0]=='image'&&newFiles.length<9){
                    newFiles.push(files[index]);
                }
            });
        }
        uploadFile(newFiles).then(res=>{
          if(firstType=='video'){
            this.videos = res;
          }else{
            this.imgs = this.imgs.concat(res);
          }
        }).catch(err=>{
          this.$message({
            message:err.msg,
            type:"error"
          });
        });
    },
    uploadSuccess(res,file,fileList){
        this.fileList = fileList;
    },

    showAddPost(){
      this.showAddPostState = true;
    },
    closeAddPost(){
      this.showAddPostState = false;
    },
    removepic(type,index){
      if(type=='img'){
        let imgs = this.imgs;
        imgs.splice(index,1);
        this.imgs = imgs;
      }else{
        this.videos = [];
      }
    },
    addVote(){
      this.voteList.push({
        text:"",
        image:""
      });
    },
    delVote(index){
      this.voteList.splice(index,1);
    },
    uploadVotePic(e){
      let index = e.target.getAttribute('index');
      let files = e.target.files;
      let firstType = files[0]['type'].split('/')[0];
      if(firstType!='image'){
        this.$message({
          message:"只能上传图片",
          type:"error"
        });
        return false;
      }
      uploadFile([files[0]]).then(res=>{
          this.voteList[index]['image'] = res[0]['data']['url'];
        }).catch(err=>{
          this.$message({
            message:err.msg,
            type:"error"
          });
        });
    },
    /**
     * 发布帖子
     */
    publish(){
        this.pulishCon.images = this.imgs.map(img=>{
          return img.data.url
        }).join(',');
        this.pulishCon.videos = this.videos.map(v=>{
          return v.data.url
        }).join(',');
        if(this.pulishCon.userId==''){
          this.$message({
            message:"请选择马甲号",
            type:"error"
          });
          return false;
        }
        if(this.pulishCon.categoryId==''){
          this.$message({
            message:"请选择分类",
            type:"error"
          });
          return false;
        }
        if(this.pulishCon.content==''){
          this.$message({
            message:"请输入帖子内容",
            type:"error"
          });
          return false;
        }
        if(this.pulishCon.categoryId==2){
          let haveNull = this.voteList.some((vote)=>{
              return vote['text']=='';
          });
          if(haveNull){
            this.$message({
              message:'投票选项不完整',
              type:"error"
            });
            return false;
          }
          if(this.pulishCon.voteInfo.expire==''){
            this.$message({
              message:'请选择投票截止时间',
              type:"error"
            });
            return false;
          }
          this.pulishCon.voteInfo.items = this.voteList;
        }
        publishPost(this.pulishCon).then(res=>{
          if(res.flag==1){
            this.$message({
              message:res.msg,
              type:"success"
            });
            setTimeout(()=>{
              window.location.reload();
            },500);
          }else{
            this.$message({
              message:res.msg,
              type:"error"
            });
          }
        }).catch(err=>{
          this.$message({
            message:err.msg,
            type:"error"
          })
        });
    },
    // 分页导航
    handleCurrentChange(val) {
      this.getPostData.Page = val;
      this.getData();
    },
    // 获取 easy-mock 的模拟数据
    getData() {
      const that = this;
      getPostList(that.getPostData)
        .then(res => {
          if (res.flag == 1) {
            let newData = res.data.Results.map(post => {
              post.imgArr = post.Images.split(",");
              return post;
            });
            this.postList = newData;
            this.pageSize = res.data.PageSize;
            this.postTotalCount = res.data.TotalCount;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    /**
     * 请求学校列表
     */
    _getSchoolList() {
      getSchoolList({
        type: "first"
      })
        .then(res => {
          if (res.flag == 1) {
            res.data.Results.unshift({
              schoolId: 0,
              Name: "全部"
            });
            this.schoolList = res.data.Results;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    /**
     * 请求分类数据
     */
    _getCategoryList() {
      getCatogoryList({
        type: "first"
      })
        .then(res => {
          if (res.flag === 1) {
            res.data.Results.unshift({
              CategoryId: 0,
              Name: "全部"
            });
            this.categoryList = res.data.Results;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    /**
     * 搜索
     */
    search() {
      this.getData();
    },
    /**
     * 上下架礼物
     */
    handleEdit(index, data) {
      const PostId = data.PostId;
      const type = data.IsDisplay == 1 ? "off" : "on";
      const newStatus = data.IsDisplay == 1 ? 2 : 1;
      subPost({
        type: type,
        postId: PostId
      })
        .then(res => {
          if (res.flag == 1) {
            this.$message({
              message: res.msg,
              type: "success"
            });
            this.postList[index]["IsDisplay"] = newStatus;
          } else {
            this.$message({
              message: res.msg,
              type: "error"
            });
          }
        })
        .catch(err => {
          this.$message({
            message: err.msg,
            type: "error"
          });
        });
    },
    /**
     * 预览生成二维码
     */
    preview(index) {
      const postId = this.postList[index]["PostId"];
      QRCode.toDataURL(postId)
        .then(url => {
          this.preViewCode = true;
          this.codeUrl = url;
        })
        .catch(err => {
          this.$message;
        });
    },
    /**
     * 请求用户列表
     */
    _getUserList() {
      getUserList({
        Identity: 2
      })
        .then(res => {
          if (res.flag == 1) {
            this.userList = res.data.Results;
          } else {
            this.$message({
              message: res.msg,
              type: "success"
            });
          }
        })
        .catch(err => {
          this.$message({
            message: err.msg,
            type: "error"
          });
        });
    },
    /**
     * 隐藏弹出层
     */
    closePreview() {
      this.preViewCode = false;
      this.codeUrl = "";
    }
  }
};
</script>

<style scoped>
.add-post-form {
  padding-top: 50px;
}
.form-item {
  margin-bottom: 30px;
  overflow: hidden;
}
.form-item .form-item-title {
  display: inline-block;
  width: 15%;
  text-align: right;
  vertical-align: top;
  padding-top: 5px;
}
.post-con {
  width: 83%;
}
.source-list{
    width: 85%;
    float: right;
}
.source-list .source-item{
    position: relative;
    width: 150px;
    height: 150px;
    border:1px solid #DCDFE6;
    border-radius: 4px;
    float: left;
    margin-right: 5px;
    line-height: 150px;
    text-align: center;
}
.source-item .remove-btn{
  font-size: 20px;
  top:10px;
  right: 10px;
  background: rgba(0, 0, 0, .7);
  color:#fff;
}
.source-item img{
  display: block;
  width: 100%;
  height: 100%;
}
.uploadFile{
    width: 100%;
    height: 100%;
    position: absolute;
    top:0;
    left:0;
    opacity:0;
}
.el-icon-plus{
    font-size: 30px;
    color:#DCDFE6;
}
.add-post-btn {
  float: right;
}
.el-carousel__button {
  width: 10px;
}
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}
.handle-select-sub{
  width: 83%;
}
.handle-input {
  width: 200px;
  display: inline-block;
}
.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.source-box {
  width: 300px;
  height: 150px;
}
.source {
  margin: o auto;
  height: 100%;
}
.user-head {
  width: 60px;
  height: 60px;
}
.pre-view-box {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.7);
  z-index: 99;
}
.pre-view-box img,.pre-view-box video {
  width: 200px;
  height: 200px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -100px;
  margin-left: -100px;
}
.el-breadcrumb {
  line-height: 2;
}
.add-vest {
  float: right;
}
.add-post-box {
  width: 100%;
  height: 100%;
  background:#fff;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 99;
  overflow-y: scroll;
}
.el-icon-close {
  font-size: 40px;
  position: absolute;
  top: 50px;
  right: 100px;
  cursor: pointer;
}
.add-post-form {
  width: 700px;
  height: 100%;
  margin: 0 auto;
  padding-bottom: 80px;
}
.vote-list{
  width: 85%;
  float: right;
}
.vote-list li{
  list-style: none;
  overflow: hidden;
}
.vote-list li .img-box{
  position: relative;
  width: 100px;
  height: 100px;
  display: block;
  border:1px solid #DCDFE6;
  text-align: center;
  line-height: 100px;
  margin-right: 20px;
  float: left;
  margin-bottom: 20px;
}
.vote-list li .img-box img{
  width:100%;
  height:100%;
}
.vote-list li .txt-box{
  width: 380px;
  height: 100px;
  display: block;
  float: left;
  display: flex;
  align-items: center;
}
.txt-input{
  width: 300px;
  margin-right: 10px;
}
.voteTypeSwitch{
  margin-top:8px;
}
</style>
